package com.zhiyume.api.controller;

import com.zhiyume.api.util.ApiClassifyEnum;
import com.zhiyume.api.util.ApiConstants;
import com.zhiyume.api.util.ApiFloorEnum;
import com.zhiyume.api.util.ApiOperateEnum;
import com.zhiyume.controller.BaseController;
import com.zhiyume.dao.api.TCmsHomeMapper;
import com.zhiyume.dao.api.TCmsTemplateMapper;
import com.zhiyume.dao.api.TInformationMapper;
import com.zhiyume.dao.api.TInformationSelfMapper;
import com.zhiyume.dao.entity.*;
import com.zhiyume.page.PageReq;
import com.zhiyume.page.Pager;
import com.zhiyume.service.CmsHomeService;
import com.zhiyume.service.CmsRecommendService;
import com.zhiyume.service.InformationService;
import com.zhiyume.service.RedisService;
import com.zhiyume.service.common.ConstantEnum;
import com.zhiyume.service.util.DateUtil;
import com.zhiyume.service.util.JsonUtil;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.TypeConstants;
import com.zhiyume.vo.CommonReqVO;
import com.zhiyume.vo.NavReqVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

import static com.zhiyume.util.TypeConstants.CmsResource.HOME_PAGE_TYPE;
import static com.zhiyume.util.TypeConstants.HomePageConstants.RECOMMEND_TYPE;

/**
 * Created by wang on 17/10/20.
 */
@RestController
@RequestMapping("/")
public class HomePageAction extends BaseController{

    @Autowired
    private InformationService informationService;
    @Autowired
    private CmsHomeService cmsHomeService;

    @Autowired
    private CmsRecommendService cmsRecommendService;

    @Autowired
    TInformationMapper tInformationMapper;
    @Autowired
    TInformationSelfMapper tInformationSelfMapper;
    @Autowired
    TCmsHomeMapper tCmsHomeMapper;
    @Autowired
    private RedisService redisService;

    @Autowired
    TCmsTemplateMapper tCmsTemplateMapper;

    private String successType = ConstantEnum.CONSTANT_SUCCESS.getErrType();
    private String successMsg = ConstantEnum.CONSTANT_SUCCESS.getErrMsg();

    private int STATUS_PUBLISHED = Integer.valueOf((String)TypeConstants.statusMap.get(TypeConstants.STATUS_PUBLISHED));
    private String SLIDER_FLOOR = (String)TypeConstants.floorMap.get(TypeConstants.SLIDER_FLOOR);

    private static final Log log = LogFactory.getLog(HomePageAction.class.getName());

    /**
     * 至娱官网
     */
    @RequestMapping(value = "/index")
    public ModelAndView homePage(@RequestParam(value="type",defaultValue = "99")Integer type, Model model){

        ModelAndView mv = new ModelAndView();
        mv.setViewName("page/home/index");

        //获取官网轮播推荐数据===================
        PageReq recommend = new PageReq();
        recommend.setHandle("refresh");
        Pager recommendSlider = new Pager();
        if(type!=99){
            try {
                recommendSlider = getClassifyShowPager(type,recommend);
            } catch (Exception e) {
                log.error(e.getMessage());
                mv.setViewName("page/error");
                mv.addObject("msg","页面被外星人劫持了");
            }
        }else{
            try {
//                recommendSlider = getHomePageSliderPager(recommend);
                recommendSlider = getWebHomePageSliderPager(recommend);
                //兼容策略
                if(CollectionUtils.isEmpty(recommendSlider.getItems())){
                    recommendSlider = getHomePageSliderPager(recommend);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                mv.setViewName("page/error");
                mv.addObject("msg","页面被外星人劫持了");
            }
        }


        List recommendSliderData = recommendSlider.getItems();
        mv.addObject("recommendSliderData",recommendSliderData);
        //=====================================

        recommend.setHandle("refresh");
        recommend.setPageSize(31);
        Pager recommendList = new Pager();
        if(type!=99){
            try {
                recommendList = getWebClassifyDataPager(type,recommend);
            } catch (Exception e) {
                log.error(e.getMessage());
                mv.setViewName("page/error");
                mv.addObject("msg","页面被外星人劫持了");
            }
        }else{
            try {
                recommendList = getWebRecommendDataPager(recommend);
            } catch (Exception e) {
                log.error(e.getMessage());
                mv.setViewName("page/error");
                mv.addObject("msg","页面被外星人劫持了");
            }
        }


        List recommendListData = recommendList.getItems();

        //add by wangxq 2018/03/06 焦点图策略更改
        List levelPoint = new ArrayList();
        if(type==99){
            getWebConfigRenderData(getLevelPointData(-1), levelPoint);
        }else{
            getWebConfigRenderData(getLevelPointData(type), levelPoint);
        }


        //add by wangxq 2018/07/10 弹窗策略更改
        getRecommend(type, mv);

        if(recommendListData.size()>=31){

            //视频专区
            CommonReqVO columnVideoReq = new CommonReqVO();
            //首页所需普通视频量
            int homeVideoNum = 8;
            columnVideoReq.setPageSize(homeVideoNum);
            columnVideoReq.setNavType(type.toString());
            columnVideoReq.setType(type);
            List<Map> recommendListRightVideo = getWebRenderData(getVideoDatas(columnVideoReq));

            boolean videoEnough = recommendListRightVideo.size()==homeVideoNum;

            mv.addObject("recommendListLeftText",recommendListData.subList(0,6));
            //add by wangxq 2018/03/06 焦点图策略更改
            mv.addObject("recommendListMiddleImg",levelPoint.size()>0?levelPoint.get(0):recommendListData.get(0));
            mv.addObject("recommendListMiddleVideo",videoEnough?
                    recommendListRightVideo.subList(4,8):recommendListData.subList(6,10));
            mv.addObject("recommendListRightVideo",videoEnough?
                    recommendListRightVideo.subList(0,2):recommendListData.subList(10,12));
            mv.addObject("recommendListRightVideo2",videoEnough?
                    recommendListRightVideo.subList(2,4):recommendListData.subList(12,14));
            mv.addObject("recommendListLeftImg1",recommendListData.get(6));
            mv.addObject("recommendListLeftImg2",recommendListData.get(7));
            mv.addObject("informationListLeft",recommendListData.subList(14,23));
            mv.addObject("informationListRightImg",recommendListData.subList(20,23));
            mv.addObject("informationListRightText",recommendListData.subList(23,30));


            int videoNum = TypeConstants.HomePageConstants.HOME_VIDEO_NUM;
            CommonReqVO videoReq = new CommonReqVO();
            videoReq.setPageSize(videoNum);
            List<Map> videos = getWebRenderData(getVideoDatas(videoReq));

            mv.addObject("videoShow",(videos.size()==videoNum)&&type==99);
            mv.addObject("videos",videos);
            mv.addObject("type",type);
        }else{
            mv.setViewName("page/error");
            mv.addObject("msg","敬请期待");
        }


        return mv;
    }

    private void getRecommend(@RequestParam(value = "type", defaultValue = "99") Integer type, ModelAndView mv) {
        List<TCmsRecommend> recommendUp;
        if(type==99){
            recommendUp= getRecommendUpData(-1);
        }else{
            recommendUp= getRecommendUpData(type);
        }
        mv.addObject("recommendUp",recommendUp.size()>0?recommendUp.get(0):new TCmsRecommend());
    }


    private Pager getHomePageSliderPager(PageReq page) throws Exception{
        return getRecommendShowPager(page);
    }

    private Pager getWebHomePageSliderPager(PageReq page) throws Exception{
        return getWebRecommendShowPager(page);
    }


    @RequestMapping("/zydownload")
    public ModelAndView downloadPage(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/page/home/download");
        return mv;
    }


    //add by wangxq 2018/03/07 视频区域数据获取
    private List<TInformationWithBLOBs> getVideoDatas(CommonReqVO reqVO){
        List<TInformationWithBLOBs> videos  = new ArrayList<>();

        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria c  = t.createCriteria();
        //类型视频
        c.andVideoUrlIsNotNull().andVideoUrlNotEqualTo("");

        //处理推荐
        if(StringUtil.isNotBlank(reqVO.getNavType())){
            if(ApiClassifyEnum.RECOMMEND.getIndex() == reqVO.getType()){
                c.andIsIntroEqualTo(TypeConstants.AppConstants.IF_INTRO);
            }else{
                c.andNavTypeEqualTo(Integer.valueOf(reqVO.getNavType()));
            }
        }
        //非草稿 //可见
        c.andStatusEqualTo(STATUS_PUBLISHED).andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);

        t.setOrderByClause("id desc,`info_id` desc");
        t.setLimitStart(0);
        t.setLimitEnd(reqVO.getPageSize());

        videos = tInformationSelfMapper.selectByExampleWithBLOBs(t);
        return videos;
    }



    //add by wangxq 2018/03/06 焦点图策略更改
    private List<TCmsHome> getLevelPointData(int type){
        List<TCmsHome> levelPoint = new ArrayList();

        CommonReqVO req = new CommonReqVO();
        req.setType(type);
        req.setStatus(TypeConstants.COMMON_VALID);
        levelPoint = cmsHomeService.getCmsHomeList(req);

        return levelPoint;
    }

    //add by wangxq 2018/03/06 焦点图策略更改
    private List<TCmsRecommend> getRecommendUpData(int type){
        List<TCmsRecommend> recommendUp = new ArrayList();

        CommonReqVO req = new CommonReqVO();
        req.setType(type);
        req.setStatus(TypeConstants.COMMON_VALID);
        recommendUp = cmsRecommendService.getCmsRecommendList(req);

        return recommendUp;
    }

    /**
     * 官网详情
     */
    @RequestMapping("/detail/{id}")
    public ModelAndView detail(@PathVariable("id") Long id) throws Exception{

        ModelAndView mv = new ModelAndView();


        if(null!=id&&id>-1){
            TInformationWithBLOBs t = informationService.findInfoById(id);
            //处理日期
            if(StringUtil.isNotBlank(t.getPublishTime())){
                Date date = DateUtils.parseDate(t.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
                mv.addObject("publishTime",DateUtil.date2String(date,"yyyy-MM-dd"));
            }
            List<TInformationWithBLOBs> tInformationList = informationService.getIntroInformationList(t.getId(),17);
            mv.addObject("tInformation",t);
            if(tInformationList.size()>=17){
                mv.addObject("list",tInformationList.subList(0,6));
                mv.addObject("list2",tInformationList.subList(6,16));
            }


            mv.addObject("pv",redisService.informationHaveRead(id));
            mv.setViewName("page/home/detail");
        }


        redisService.informationRead(id);

        return mv;
    }

    /**
     * 官网详情
     */
    @RequestMapping("/more")
    public ModelAndView more(NavReqVO page) throws Exception{

        ModelAndView mv = new ModelAndView();
        Pager p = getWebNavDataPager(page);

        mv.addObject("list",p.getItems());
        if(StringUtil.isNotBlank(page.getTitle())){
            mv.addObject("keyword",page.getTitle());
        }
        mv.addObject("flag",page.getFlag());
        mv.addObject("navType",page.getNavType());
        mv.addObject("type",page.getNavType());
        mv.setViewName("page/home/more");
        return mv;
    }
    /**
     * 官网详情
     */
    @RequestMapping("/cms")
    public ModelAndView cmsRecommend(NavReqVO page) throws Exception{

        ModelAndView mv = new ModelAndView();
        getRecommend(page.getNavType(),mv);
        if(page.getDataId()!=-1){
            TInformation t = informationService.findInfoById(page.getDataId());
            mv.addObject("imgUrl",t.getCoverUrl1());
            mv.addObject("id",t.getId());
        }
        mv.setViewName("page/building");
        return mv;
    }

    /**
     * 网站更多数据
     */
    @RequestMapping("/nav/web/list")
    @ResponseBody
    public Map queryNavWebDatas(NavReqVO page) throws Exception{
        Pager p = getWebNavDataPager(page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    //推荐轮播数据
    private Pager getWebRecommendShowPager(PageReq page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");


        TCmsHomeCriteria t = new TCmsHomeCriteria();
        TCmsHomeCriteria.Criteria ct = t.createCriteria();
        ct.andStatusEqualTo(TypeConstants.COMMON_VALID);
        //兼容焦点图配置 add by wangxq 2018/03/06
        ct.andTypeEqualTo(HOME_PAGE_TYPE.toString());

        //上下架
        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(ApiConstants.SLIDER_PAGE);

        orderByAndSetId(page, t, ct);

        p.setTotalCount(tCmsHomeMapper.countByExample(t));

        List<TCmsHome> ts = new ArrayList<TCmsHome>();

        ts = tCmsHomeMapper.selectByExample(t);
        List datas = new ArrayList();

        getConfigRenderData(ts, datas);

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    private void getConfigRenderData(List<TCmsHome> ts, List datas) {
        for(TCmsHome art:ts){
            Map temp = getConfigMap(art);
            datas.add(temp);
        }
    }

    private Map getConfigMap(TCmsHome cms) {
        Map temp = new HashMap();
        String imgUrl = cms.getImgUrl();
        String[] imgUrls = imgUrl.split(ApiConstants.IMG_SPLIT);
        temp.put("img_url", Arrays.asList(imgUrls));
        temp.put("name",cms.getFromTitle());
        TInformation info = informationService.findInfoById(cms.getFromId());
        temp.put("author",info.getAuthor());
        temp.put("link",cms.getFromId());
        temp.put("dataId",cms.getFromId());
        temp.put("video_url",info.getVideoUrl());
        Date publishTime = DateUtil.getSysDate();
        if(info.getPublishTime()!=null){
            publishTime = DateUtil.getDate(info.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
        }
        temp.put("publishTime", publishTime==null?DateUtil.getSysDate().getTime():publishTime.getTime());
        return temp;
    }

    private void getWebConfigRenderData(List<TCmsHome> ts, List datas) {
        for(TCmsHome art:ts){
            Map temp = getConfigMap(art);
            Map data = new HashMap();
            data.put("item",temp);
            datas.add(data);
        }
    }


    private Pager getRecommendShowPager(PageReq page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");


        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria ct = t.createCriteria();
        ct.andFloorTypeEqualTo(ApiFloorEnum.SLIDER.getValue()).
                andStatusEqualTo(STATUS_PUBLISHED).
                andIsIntroEqualTo(0);

        //上下架
        ct.andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);
        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(ApiConstants.SLIDER_PAGE);

        orderByAndSetId(page, t, ct);

        p.setTotalCount(tInformationMapper.countByExample(t));

        List<TInformationWithBLOBs> ts = new ArrayList<TInformationWithBLOBs>();

        ts = tInformationSelfMapper.selectByExampleWithBLOBs(t);
        List datas = new ArrayList();

        for(TInformationWithBLOBs art:ts){
            Map temp = new HashMap();
            String imgUrl = art.getCoverUrl();
            String[] imgUrls = imgUrl.split(ApiConstants.IMG_SPLIT);
            //兼容，后期需更迭
            if(StringUtil.isBlank(art.getCoverUrl1())){
                temp.put("img_url", genAppImg(imgUrls,art.getFloorType(),art.getImgStatus().toString()));
            }else {
                temp.put("img_url", genAppImg(imgUrls, art));
            }
            temp.put("name",art.getTitle());
            temp.put("author",art.getAuthor());
            temp.put("link",art.getId());
            temp.put("dataId",art.getId());
            Date publishTime = DateUtil.getSysDate();
            if(art.getPublishTime()!=null){
                publishTime = DateUtil.getDate(art.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
            }
            temp.put("publishTime", publishTime==null?DateUtil.getSysDate().getTime():publishTime.getTime());
            datas.add(temp);
        }

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }


    //普通栏目轮播数据
    private Pager getClassifyShowPager(int classify,PageReq page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");

        int id = getTemplateId(classify);

        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria ct = t.createCriteria();
        ct.andNavTypeEqualTo(id).
                andStatusEqualTo(STATUS_PUBLISHED).
                andFloorTypeEqualTo(SLIDER_FLOOR).
                andIsIntroNotEqualTo(0);

        //上下架
        ct.andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);
        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(ApiConstants.SLIDER_PAGE);

        orderByAndSetId(page, t, ct);

        p.setTotalCount(tInformationMapper.countByExample(t));

        List<TInformationWithBLOBs> ts = new ArrayList<TInformationWithBLOBs>();

        ts = tInformationSelfMapper.selectByExampleWithBLOBs(t);
        List datas = new ArrayList();

        for(TInformationWithBLOBs art:ts){
            Map temp = new HashMap();
            String imgUrl = art.getCoverUrl();
            String[] imgUrls = imgUrl.split(ApiConstants.IMG_SPLIT);
            //兼容，后期需更迭
            if(StringUtil.isBlank(art.getCoverUrl1())){
                temp.put("img_url", genAppImg(imgUrls,art.getFloorType(),art.getImgStatus().toString()));
            }else {
                temp.put("img_url", genAppImg(imgUrls, art));
            }
            temp.put("name",art.getTitle());
            temp.put("link",art.getId());
            temp.put("author",art.getAuthor());
            temp.put("dataId",art.getId());
            Date publishTime = DateUtil.getSysDate();
            if(art.getPublishTime()!=null){
                publishTime = DateUtil.getDate(art.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
            }
            temp.put("publishTime", publishTime==null?DateUtil.getSysDate().getTime():publishTime.getTime());
            datas.add(temp);
        }

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }


    //获取模板id
    private int getTemplateId(int classify) {
        return classify;
    }

    //网页推荐列表数据获取
    private Pager getWebRecommendDataPager(PageReq page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");


        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria ct = t.createCriteria();
        //速度会有些慢
        List<String> codes = new ArrayList<>();
        codes.add(ApiFloorEnum.SLIDER.getValue());
        codes.add(ApiFloorEnum.TOP.getValue());
        ct.andFloorTypeNotIn(codes).andStatusEqualTo(STATUS_PUBLISHED).
                andIsIntroEqualTo(TypeConstants.AppConstants.IF_INTRO);

        //上下架
        ct.andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);

        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(page.getPageSize());

        orderByAndSetId(page, t, ct);

        p.setTotalCount(tInformationMapper.countByExample(t));


        List<TInformationWithBLOBs> ts = new ArrayList<TInformationWithBLOBs>();

        ts = tInformationSelfMapper.selectByExampleWithBLOBs(t);
        List<Map> datas = new ArrayList<Map>();

        if(ApiOperateEnum.REFRESH.getName().equals(page.getHandle())){
            List<Map> top = getWebRecommendTopData();
            if(CollectionUtils.isNotEmpty(top)){
                datas.addAll(top);
            }
        }

        datas.addAll(getWebRenderData(ts));

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    //网页普通栏目数据
    private Pager getWebClassifyDataPager(int classify,PageReq page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");

        int id = getTemplateId(classify);

        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria ct = t.createCriteria();
        //速度会有些慢
        List<String> codes = new ArrayList<>();
        codes.add(ApiFloorEnum.SLIDER.getValue());
        codes.add(ApiFloorEnum.TOP.getValue());
        ct.andNavTypeEqualTo(id).
                andFloorTypeNotIn(codes).
                andStatusEqualTo(STATUS_PUBLISHED).
                andIsIntroNotEqualTo(TypeConstants.AppConstants.IF_INTRO);
        //上下架
        ct.andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);

        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(page.getPageSize());

        orderByAndSetId(page, t, ct);

        p.setTotalCount(tInformationMapper.countByExample(t));


        List<TInformationWithBLOBs> ts = new ArrayList<TInformationWithBLOBs>();

        ts = tInformationSelfMapper.selectByExampleWithBLOBs(t);
        List<Map> datas = new ArrayList<Map>();

        if(ApiOperateEnum.REFRESH.getName().equals(page.getHandle())){
            List<Map> top = getWebTopData(id);
            if(CollectionUtils.isNotEmpty(top)){
                datas.addAll(top);
            }
        }

        datas.addAll(getWebRenderData(ts));

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    //获取网页栏目数据
    private Pager getWebNavDataPager(NavReqVO page) throws Exception{
        Pager p = new Pager();

        if(page.getPageSize()>ApiConstants.MAX_NUM)
            throw new Exception("pageSize超负荷");


        //基础服务搜索相关
        TInformationCriteria total = new TInformationCriteria();
        TInformationCriteria.Criteria cBase = total.createCriteria();
        //速度会有些慢  上下架
        cBase.andStatusEqualTo(STATUS_PUBLISHED).andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);

        TInformationCriteria total_author = new TInformationCriteria();
        TInformationCriteria.Criteria cAuthor = total_author.createCriteria();
        //速度会有些慢  上下架
        cAuthor.andStatusEqualTo(STATUS_PUBLISHED).andIsShowEqualTo(TypeConstants.AppConstants.IF_INFO_SHOW);

        //搜索名称
        if(StringUtil.isNotBlank(page.getTitle())){

            cBase.andTitleLike("%"+page.getTitle()+"%");
            cAuthor.andAuthorLike("%"+page.getTitle()+"%");
            total.or(cAuthor);
        }

        //视频 add by wangxq6 20180307
        if(TypeConstants.HomePageConstants.VIDEO_FLAG==page.getFlag()){
            cBase.andVideoUrlNotEqualTo("").andVideoUrlIsNotNull();
        }


        //栏目 add by wangxq6 20180315
        if(page.getNavType()!=RECOMMEND_TYPE){
            cBase.andNavTypeEqualTo(page.getNavType());
        }

        if(page.getDataId() > -1){
            //搜索数据行为
            page.setHandle(ApiOperateEnum.DOWN.getName());
        }

        //翻页
        total.setLimitStart(0);
        total.setLimitEnd(page.getPageSize());

        orderByAndSetId(page, total, cBase);

        p.setTotalCount(tInformationMapper.countByExample(total));


        List<TInformationWithBLOBs> ts = new ArrayList<TInformationWithBLOBs>();

        ts = tInformationSelfMapper.selectByExampleWithBLOBs(total);
        List<Map> datas = new ArrayList<Map>();

        datas.addAll(getWebRenderData(ts));

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }


    private List<TInformationWithBLOBs> genInformationData(int id) {
        TInformationCriteria top = new TInformationCriteria();
        TInformationCriteria.Criteria ctop = top.createCriteria();
        top.setOrderByClause("id desc,`info_id` desc");
        top.setLimitStart(0);
        top.setLimitEnd(1);
        ctop.andNavTypeEqualTo(id)
                .andFloorTypeEqualTo(ApiFloorEnum.TOP.getValue())
                .andIsIntroNotEqualTo(TypeConstants.AppConstants.IF_INTRO);
        List<TInformationWithBLOBs> ts = new ArrayList<TInformationWithBLOBs>();

        ts = tInformationSelfMapper.selectByExampleWithBLOBs(top);
        return ts;
    }

    //普通栏目置顶数据
    private List<Map> getWebTopData(int id){
        List<TInformationWithBLOBs> ts = genInformationData(id);
        return getWebRenderData(ts);
    }

    private List<TInformationWithBLOBs> getRecommendInforData() {
        TInformationCriteria top = new TInformationCriteria();
        TInformationCriteria.Criteria ctop = top.createCriteria();
        top.setOrderByClause("id desc,`info_id` desc");
        top.setLimitStart(0);
        top.setLimitEnd(1);
        ctop.andFloorTypeEqualTo(ApiFloorEnum.TOP.getValue()).
                andIsIntroEqualTo(TypeConstants.AppConstants.IF_INTRO);
        List<TInformationWithBLOBs> ts = new ArrayList<TInformationWithBLOBs>();

        ts = tInformationSelfMapper.selectByExampleWithBLOBs(top);
        return ts;
    }


    //推荐的置顶数据
    private List<Map> getWebRecommendTopData(){
        List<TInformationWithBLOBs> ts = getRecommendInforData();
        return getWebRenderData(ts);
    }


    private List<Map> getWebRenderData(List<TInformationWithBLOBs> ts) {
        List<Map> datas = new ArrayList<Map>();
        for(TInformationWithBLOBs art:ts){
            Map temp = new HashMap();
            Map dataItem = new HashedMap();
            String imgUrl = art.getCoverUrl();
            String[] imgUrls = imgUrl.split(ApiConstants.IMG_SPLIT);
            //兼容，后期需更迭
            if(StringUtil.isBlank(art.getCoverUrl1())){
                temp.put("img_url", genAppImg(imgUrls,art.getFloorType(),art.getImgStatus().toString()));
            }else{
                temp.put("img_url", genAppImg(imgUrls,art));
            }

            temp.put("name",art.getTitle());
            temp.put("link",art.getId());
            temp.put("dataId",art.getId());
            temp.put("author",art.getAuthor());
            temp.put("video_url",art.getVideoUrl());
            Date publishTime = DateUtil.getSysDate();
            if(art.getPublishTime()!=null){
                publishTime = DateUtil.getDate(art.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
            }
            temp.put("publishDate",publishTime);
            temp.put("publishTime", publishTime==null?DateUtil.getSysDate().getTime():publishTime.getTime());
            //图文专区有两种
            if(art.getFloorType().equals(TypeConstants.floorMap.get(TypeConstants.IMAGE_FLOOR))){
                dataItem.put("code",art.getImgStatus().toString());
            }else{
                dataItem.put("code",art.getFloorType());
            }

            dataItem.put("item",temp);
            datas.add(dataItem);
        }
        return datas;
    }

    //设置dataId以及封装条件
    private void orderByAndSetId(PageReq page, TInformationCriteria t, TInformationCriteria.Criteria ct) {
        if(ApiOperateEnum.UP.getName().equals(page.getHandle())){
            ct.andIdGreaterThan(page.getDataId());
            t.setOrderByClause("id asc,`info_id` asc");
        }
        else if(ApiOperateEnum.DOWN.getName().equals(page.getHandle())){
            ct.andIdLessThan(page.getDataId());
            t.setOrderByClause("id desc,`info_id` desc");
        }else if(ApiOperateEnum.REFRESH.getName().equals(page.getHandle())){
            t.setOrderByClause("id desc,`info_id` desc");
        }else{
            t.setOrderByClause("id desc,`info_id` desc");
        }
    }


    //设置cms的dataId以及封装条件
    private void orderByAndSetId(PageReq page, TCmsHomeCriteria t, TCmsHomeCriteria.Criteria ct) {
        if(ApiOperateEnum.UP.getName().equals(page.getHandle())){
            ct.andIdGreaterThan(page.getDataId());
            t.setOrderByClause("id asc,`h_id` asc");
        }
        else if(ApiOperateEnum.DOWN.getName().equals(page.getHandle())){
            ct.andIdLessThan(page.getDataId());
            t.setOrderByClause("id desc,`h_id` desc");
        }else if(ApiOperateEnum.REFRESH.getName().equals(page.getHandle())){
            t.setOrderByClause("id desc,`h_id` desc");
        }else{
            t.setOrderByClause("id desc,`h_id` desc");
        }
    }

    private List<String> genAppImg(String[] imgUrls,TInformationWithBLOBs art){

        List<String> urls = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(Arrays.asList(imgUrls))){
            if(imgUrls.length == 1){
                urls.add(art.getCoverUrl1());
            }else if(imgUrls.length == 2){
                urls.add(art.getCoverUrl1());
                urls.add(art.getCoverUrl2());

            }else if(imgUrls.length == 3){
                urls.add(art.getCoverUrl1());
                urls.add(art.getCoverUrl2());
                urls.add(art.getCoverUrl3());

            }
        }

        return urls;
    }

    private List<String> genAppImg(String[] imgUrls,String code,String imgStatus){

        List<String> urls = new ArrayList<>();
        informationService.genAppImg(imgUrls,code,imgStatus);

        return urls;
    }

}
